import { TreeGridSchema } from '../schema/treegrid';
import FdCollectionBaseComponent from '../../common/collection-base/fd-collection-base';
import { ElementPropertyConfig } from '@farris/ide-property-panel';
import { TreeGridProp } from '../property/property-config';
import FdTreeGridFieldComponent from './treegrid-field/component/fd-treegrid-field';
import { ControlService } from '../../../../service/control.service';
import { defaultsDeep } from 'lodash-es';
import { SchemaService } from '@farris/designer-services';

export default class FdTreeGridComponent extends FdCollectionBaseComponent {

    /** 单列实例集合 */
    gridFieldInstances: FdTreeGridFieldComponent[];

    constructor(component: any, options: any) {
        super(component, options);

        this.customToolbarConfigs = [
            {
                id: 'fieldManager',
                title: '字段维护',
                icon: 'f-icon f-icon-home-setup',
                click: (e) => {
                    e.stopPropagation();
                    this.showFieldManager();
                }
            }
        ];
    }

    getDefaultSchema(): any {
        return TreeGridSchema;
    }

    getStyles(): string {
        return 'display: flex; flex: 1; padding:0;border:0;';
    }

    init() {
        this.adaptOldControlSchema();
        this.components = [];
        this.gridFieldInstances = [];
        if (this.component.fields) {
            const options = Object.assign({}, this.options, { parent: this });

            this.component.fields.map(item => {
                const fieldInstance = new FdTreeGridFieldComponent(item, options, this);
                this.gridFieldInstances.push(fieldInstance);
            });
        }

    }
    render(): any {

        return super.render(this.renderTemplate('TreeGrid', {
            component: this.component,
            gridFieldInstances: this.gridFieldInstances
        }));
    }
    /**
     * 元素扩展事件
     */
    attach(element: HTMLElement): Promise<any> {
        const superAttach = super.attach(element);

        // 挂载单列的点击事件
        this.gridFieldInstances.forEach(gridFieldInstance => {
            const itemId = gridFieldInstance.component.id;
            this.loadRefs(element, {
                [itemId]: 'multiple'
            });
            gridFieldInstance.attach(this.refs[itemId][0]);
        });

        // 挂载可拖拽区域，用于从控件工具箱和实体树中拖拽节点
        this.hook('attachComponents', element, [], [], this);

        this.registerGridFieldDnd();

        return superAttach;
    }
    /**
     * 组装属性面板配置数据
     */
    getPropertyConfig(): ElementPropertyConfig[] {
        const serviceHost = this.options.designerHost;
        const prop: TreeGridProp = new TreeGridProp(serviceHost, this.viewModelId, this.componentId);
        const propertyConfig: ElementPropertyConfig[] = prop.getPropConfig(this.component);
        return propertyConfig;
    }

    /**
     * 调整列顺序后同步修改DOM结构
     */
    dragGridFieldEnd(e: any) {
        super.dragGridFieldEnd(e);

        const oldIndex = e.oldIndex;
        const newIndex = e.newIndex;
        const item = this.gridFieldInstances[oldIndex];
        this.gridFieldInstances.splice(oldIndex, 1);
        this.gridFieldInstances.splice(newIndex, 0, item);
    }


    /**
     * 适配表单控件的元数据变更
     */
    private adaptOldControlSchema() {
        // 适配列编辑器内的控件元数据
        if (this.component.fields && this.component.fieldEditable) {
            const injector = this.options.designerHost.getService('Injector');
            const controlService = injector.get(ControlService) as ControlService;

            this.component.fields.forEach(field => {
                if (!field.editor) {
                    return;
                }
                const metadata = controlService.getControlMetaData(field.editor.type);
                field.editor = defaultsDeep(field.editor, metadata);
            });
        }
        // 适配旧表单中展开层级为null的情况
        if (this.component.expandLevel === null) {
            this.component.expandLevel = -1;
        }

        // 适配实体中分级码字段修改label的场景
        const schemaService = this.options.designerHost.getService('SchemaService') as SchemaService;
        const udtFields = schemaService.getTreeGridUdtFields(this.viewModelId);
        if (udtFields && udtFields.length) {
            const udtExisted = udtFields.find(f => f.key === this.component.udtField);
            if (!udtExisted) {
                this.component.udtField = udtFields[0].key;
            }
        } else {
            this.component.udtField = '';
        }

    }

}
